# -*- coding: utf-8 -*- 
# 作者:飞虎
# 开发时间:2022/6/2 21:26
from PyQt5.Qt import *


class Window(QWidget):
	def __init__(self):
		super().__init__()
		self.setWindowTitle('QTreeWidget学习')
		self.resize(500, 500)
		self.setup_ui()

	def setup_ui(self):
		operatorlayout = QHBoxLayout()
		addBtn = QPushButton('添加节点')
		updateBtn = QPushButton('修改节点')
		deleteBtn = QPushButton('删除节点')
		operatorlayout.addWidget(addBtn)
		operatorlayout.addWidget(updateBtn)
		operatorlayout.addWidget(deleteBtn)
		addBtn.clicked.connect(self.addNode)
		updateBtn.clicked.connect(self.updateNode)
		deleteBtn.clicked.connect(self.deleteNode)

		self.tree = QTreeWidget()
		self.tree.setColumnCount(2)

		self.tree.setHeaderLabels(['Key','Value'])

		# 添加根节点
		root = QTreeWidgetItem(self.tree)
		root.setText(0,'根节点')
		root.setIcon(0,QIcon('./Icons/android_96px_1.ico'))

		# 添加子节点
		child1 = QTreeWidgetItem(root)
		child1.setText(0,'子节点1')
		child1.setText(1,'1')

		child2 = QTreeWidgetItem(root)
		child2.setText(0, '子节点2')
		child2.setText(1, '2')
		child2.setIcon(0,QIcon('./Icons/android_96px_1.ico'))

		child2_1 = QTreeWidgetItem(child2)
		child2_1.setText(0,'子节点3')
		child2_1.setText(1,'3')

		self.tree.expandAll()
		self.tree.clicked.connect(self.onTreeClicked)

		mainLayout = QVBoxLayout(self)
		mainLayout.addLayout(operatorlayout)
		mainLayout.addWidget(self.tree)
		self.setLayout(mainLayout)

	def onTreeClicked(self,index):
		item = self.tree.currentItem()
		print(index.row())
		print('key=%s,value=%s' % (item.text(0),item.text(1)))
		

	def addNode(self):
		print('添加节点')
		item = self.tree.currentItem()
		print(item)
		node = QTreeWidgetItem(item)
		node.setText(0,'新节点')
		node.setText(1,'新值')
		

	def updateNode(self):
		print('修改节点')
		item = self.tree.currentItem()
		text,ok = QInputDialog.getText(self,'输入节点名称','节点名称:')
		if ok and text:
			item.setText(0,text)
			text,ok = QInputDialog.getText(self,'输入节点值','节点的值')
			if ok and text:
				item.setText(1,text)


	def deleteNode(self):
		print('删除节点')
		item = self.tree.currentItem()
		root= self.tree.invisibleRootItem()
		for item in self.tree.selectedItems():
			(item.parent() or root).removeChild(item)







if __name__ == '__main__':
	import sys

	app = QApplication(sys.argv)
	window = Window()
	window.show()
	sys.exit(app.exec_())